import nativeBridge from '@/assets/js/nativeBridge'

export const handleBackMixin = {
  mounted() {
    // 页面加载时， 设置Android返回拦截
    // this.handleNativeBack 拦截方法
    nativeBridge.handleNativeBack(() => {
      // 全局confirm、loading关闭
      const confirmEl = document.querySelector('body>.vux-confirm .vux-x-dialog .weui-dialog')
      if (confirmEl && confirmEl.style.display !== 'none') {
        this.$vux.confirm.hide()
        return true
      }
      const loadingEl = document.querySelector('body>.vux-loading')
      if (loadingEl && loadingEl.style.display !== 'none') {
        this.$vux.loading.hide()
        return true
      }
      return this.handleNativeBack() === true
    })

    // 监听所有的弹窗，弹窗打开时，禁用IOS侧滑返回
    this.allPopupModels.forEach(item => {
      // this.$watch(item, function (val) {
      //   if (val) {
      //     nativeBridge.toggleIOSBack(true)
      //   } else {
      //     nativeBridge.toggleIOSBack(false)
      //   }
      // })
    })
  },
  activated() {
    nativeBridge.handleNativeBack(() => {
      const confirmEl = document.querySelector('.vux-confirm .vux-x-dialog .weui-dialog')
      if (confirmEl && confirmEl.style.display !== 'none') {
        this.$vux.confirm.hide()
        return true
      }
      const loadingEl = document.querySelector('.vux-loading')
      if (loadingEl && loadingEl.style.display !== 'none') {
        this.$vux.loading.hide()
        return true
      }
      return this.handleNativeBack() === true
    })
  },
  methods: {
    handleNativeBack() {
      let allClose = true
      this.allPopupModels.forEach(item => {
        if (this[item]) {
          allClose = false
          this[item] = false
        }
      })
      if (allClose) {
        if (this.$route.name === 'Home' || this.$route.name === 'Address' || this.$route.name === 'MeiTu' || this.$route.name === 'Cart' || this.$route.name === 'user') {
          return false
        }
        this.$router.go(-1)
      }
      return true
    }
  }
}

// 默认状态栏字体颜色为白色。需要黑色的页面才引入
export const statusBarMixin = {
  data() {
    return {
      statusBarColor: 'black'
    }
  },
  created() {
    nativeBridge.setStatusBar(this.statusBarColor)
  },
  activated() {
    nativeBridge.setStatusBar(this.statusBarColor)
  },
  watch: {
    statusBarColor() {
      nativeBridge.setStatusBar(this.statusBarColor)
    }
  }
}
